#include "uieditorwidget.h"
#include "ui_uieditorwidget.h"
#include <QDebug>
#include <QHBoxLayout>
#include "EditorWidgets/searchlineedit.h"
UIEditorWidget::UIEditorWidget(QWidget* parent) :
    QMainWindow(parent),
    ui(new Ui::UIEditorWidget)
{
    ui->setupUi(this);
    this->setWindowModality(Qt::ApplicationModal);
    ui->widget->setMinimumSize(ui->Width->text().toFloat(),ui->Height->text().toFloat());
    ui->widget->setLayout(new QHBoxLayout());
    ui->tabWidget->setMinimumWidth(400);
    ui->detailTabWidget->setMinimumWidth(400);
    this->setWindowIcon(QIcon(":/res/icon/ui.png"));

    this->setAcceptDrops(true);
    this->setCentralWidget(ui->centerWidget);

    ui->dockWidget->setFeatures(QDockWidget::AllDockWidgetFeatures);
    this->addDockWidget(Qt::LeftDockWidgetArea,ui->dockWidget);
    ui->dockWidget->setTitleBarWidget(new QWidget());

    ui->dockWidget_2->setFeatures(QDockWidget::AllDockWidgetFeatures);
    this->addDockWidget(Qt::RightDockWidgetArea,ui->dockWidget_2);
    ui->dockWidget_2->setTitleBarWidget(new QWidget());


    InitLineEdit();
    InitBtns();
    InitEditUI();
    InitListWidget();
    //编辑名字窗口
    connect(l,&QLineEdit::editingFinished,this,&UIEditorWidget::EditFinished);
    //右边的detail无效
    connect(ui->tabWidget,&QTabWidget::currentChanged,[=](int index){
        if(index == 0)
        {
            ui->detailTabWidget->setTabEnabled(2,false);
            if(!ui->kjWidget->currentItem() && ui->kjWidget->count() > 0)
                ui->kjWidget->setCurrentRow(0);
            bool isLabel = true;
            if(ui->kjWidget->count() > 0)
            {
                isLabel = UILib::Instance().labels.contains(ui->kjWidget->currentItem()->text());
                ui->detailTabWidget->setTabEnabled(1,isLabel);
                ui->detailTabWidget->setTabEnabled(0,!isLabel);
            }
            else
            {
                ui->detailTabWidget->setTabEnabled(1,true);
                ui->detailTabWidget->setTabEnabled(0,true);
            }
        }
        else
        {
            ui->detailTabWidget->setTabEnabled(2,true);
            ui->detailTabWidget->setTabEnabled(0,false);
            ui->detailTabWidget->setTabEnabled(1,false);
        }
    });
    //发送控件信息
    connect(&EventCenter::Instance(),&EventCenter::GetDragKJInfo,this,[=](){
        InformInfo();
    });
    Load();
}

UIEditorWidget::~UIEditorWidget()
{
    delete ui;
    delete curWidget;
}

void UIEditorWidget::AddLabel(LabelInfo* info)
{
    if(!info)
    {
        info = new LabelInfo();
        info->name = ui->kjWidget->currentItem()->text();
    }
    UILib::Instance().labels.insert(info->name,info);
    ui->detailTabWidget->setTabEnabled(1,true);
    ui->detailTabWidget->setTabEnabled(0,false);
    LoadLabel(info);
}

void UIEditorWidget::AddButton(ButtonInfo* info)
{
    if(!info)
    {
        info = new ButtonInfo();
        info->name = ui->kjWidget->currentItem()->text();
    }
    UILib::Instance().btns.insert(info->name,info);
    ui->detailTabWidget->setTabEnabled(1,false);
    ui->detailTabWidget->setTabEnabled(0,true);
    LoadButton(info);
}

void UIEditorWidget::AddWidget(MyWidget* w)
{
    if(!w)
    {
        w = new MyWidget();
        if(ui->windowWidget->count() > 0)
            w->name = ui->windowWidget->item(ui->windowWidget->count() - 1)->text();
    }
    widgets.insert(w->name,w);
}

LabelInfo *UIEditorWidget::GetCurLabelInfo()
{
    QString name = ui->kjWidget->currentItem()->text();
    if(!UILib::Instance().labels.contains(name))
        return nullptr;
    return UILib::Instance().labels[name];
}

ButtonInfo *UIEditorWidget::GetCurButtonInfo()
{
    QString name = ui->kjWidget->currentItem()->text();
    if(!UILib::Instance().btns.contains(name))
        return nullptr;
    return UILib::Instance().btns[name];
}

void UIEditorWidget::closeEvent(QCloseEvent *event)
{
    QWidget::closeEvent(event);
    Save();
}

void UIEditorWidget::dragEnterEvent(QDragEnterEvent *event)
{
    event->acceptProposedAction();
}

void UIEditorWidget::dropEvent(QDropEvent *event)
{
    ResourceListWidget * w = dynamic_cast<ResourceListWidget*>(event->source());
    if(!w) return;
    QString path = w->GetCurItemPath();
    QDir d;
    path = d.relativeFilePath(path);

    switch(ui->detailTabWidget->currentIndex())
    {
    case 0:
        //按钮
        DropBtn(path);
        break;
    case 1:
        //Label
        DropLabel(path);
        break;
    case 2:
        //界面
        DropWidget(path);
        break;
    default:break;
    }
    DropAlbum(path);
}

void UIEditorWidget::DropBtn(QString path)
{
    QPoint pos = ui->detailTabWidget->currentWidget()->mapFromGlobal(QCursor::pos());
    FileManager::FileType type = (FileManager::FileType)FileManager::Instance().GetFileType(path);
    if(type == FileManager::SOUND && ui->btnSoundPath->geometry().contains(pos))
    {
        ui->btnSoundPath->setText(path);
    }
    else if(type == FileManager::IMAGE && ui->btnImgPath->geometry().contains(pos))
    {
        ui->btnImgPath->setText(path);
    }
    else if(type == FileManager::IMAGE && ui->btnInPath->geometry().contains(pos))
    {
        ui->btnInPath->setText(path);
    }
    else if(type == FileManager::IMAGE && ui->btnPressPath->geometry().contains(pos))
    {
        ui->btnPressPath->setText(path);
    }
}

void UIEditorWidget::DropLabel(QString path)
{
    QPoint pos = ui->detailTabWidget->currentWidget()->mapFromGlobal(QCursor::pos());
    FileManager::FileType type = (FileManager::FileType)FileManager::Instance().GetFileType(path);
    if(type == FileManager::IMAGE && ui->labelImgPath->geometry().contains(pos))
    {
        ui->labelImgPath->setText(path);
    }
}

void UIEditorWidget::DropWidget(QString path)
{
    QPoint pos = ui->detailTabWidget->currentWidget()->mapFromGlobal(QCursor::pos());
    FileManager::FileType type = (FileManager::FileType)FileManager::Instance().GetFileType(path);
    if(type == FileManager::IMAGE && ui->widgetImg->geometry().contains(pos))
    {
        ui->widgetImg->setText(path);
    }
}

void UIEditorWidget::DropAlbum(QString path)
{
    QPoint pos = this->mapFromGlobal(QCursor::pos());
    FileManager::FileType type = (FileManager::FileType)FileManager::Instance().GetFileType(path);
    if(type == FileManager::IMAGE && ui->albumListDockWidget->geometry().contains(pos))
    {
        ui->albumList->addItem(path);
        ui->albumList->item(ui->albumList->count() - 1)->setToolTip(path);
        emit EventCenter::Instance().AddAlbum(path);
    }
}

void UIEditorWidget::InitBtns()
{
    connect(ui->yesBtn,&QPushButton::clicked,this,[=](){
        ui->widget->setMinimumSize(ui->Width->text().toFloat(),ui->Height->text().toFloat());
    });
    connect(ui->AddBtnBtn,&QPushButton::clicked,this,[=](){
        ui->kjWidget->addItem(defaulTName + QString::number(id));
        ui->kjWidget->setCurrentRow(ui->kjWidget->count() - 1);
        id++;
        AddButton();
    });
    connect(ui->AddLabelBtn,&QPushButton::clicked,this,[=](){
        ui->kjWidget->addItem(defaulTName + QString::number(id));
        ui->kjWidget->setCurrentRow(ui->kjWidget->count() - 1);
        id ++ ;
        AddLabel();
    });
    connect(ui->AddWidgetBtn,&QPushButton::clicked,this,[=](){
        ui->windowWidget->addItem(defaulTName + QString::number(id));
        AddWidget();
        ui->windowWidget->setCurrentRow(ui->windowWidget->count() - 1);
        id++;
    });
    //删除控件
    connect(ui->deleteKjBtn,&QPushButton::clicked,this,[=](){
        if(ui->windowWidget->count() <= 0)
            return;
        widgets[ui->windowWidget->currentItem()->text()]->DeleteSelected();
    });
    connect(ui->DeleteBtn,&QPushButton::clicked,this,[=](){
        DeleteItem();
    });
    connect(ui->DeleteWidgetBtn,&QPushButton::clicked,this,[=](){
        DeleteWidget();
    });
    //颜色选择器
    colorDialog.setModal(true);
    colorDialog.setCurrentColor("black");
    //点击按钮打开颜色选择器
    connect(ui->ButtonColor,&QPushButton::clicked,this,[=](){
        colorDialog.show();
    });
    connect(ui->LabelColor,&QPushButton::clicked,this,[=](){
        colorDialog.show();
    });
    connect(&colorDialog,&QColorDialog::colorSelected,this,[=](){
        if(ui->kjWidget->count() <= 0)
            return;
        int r = colorDialog.currentColor().red();
        int g = colorDialog.currentColor().green();
        int b = colorDialog.currentColor().blue();
        QString qss = "background-color:rgb(" +
                QString::number(r) + "," +
                QString::number(g) + "," +
                QString::number(b) + ");border:none;";
        if(ui->detailTabWidget->currentIndex() == 0)
        {
            //button
            ui->ButtonColor->setStyleSheet(qss);
        }
        else
        {
            //label
            ui->LabelColor->setStyleSheet(qss);
            ui->textEdit->setTextColor(colorDialog.currentColor());
        }
    });
    connect(ui->LabelFontBox,&QFontComboBox::currentFontChanged,this,[=](){
        ui->textEdit->setFontFamily(ui->LabelFontBox->currentFont().family());
    });
    void (QSpinBox:: *spinBoxSignal)(int) = &QSpinBox::valueChanged;
    connect(ui->LabelFontSize,spinBoxSignal,this,[=](int i){
        ui->textEdit->setFontPointSize(i);
    });
}

void UIEditorWidget::InitLineEdit()
{
    l = new QLineEdit();
    l->setWindowModality(Qt::ApplicationModal);
    l->setWindowIcon(QIcon(":/res/icon/ui.png"));
    l->setWindowTitle("编辑名字");
    l->setText(defaulTName + QString::number(id));
    l->setFont(QFont("宋体",10));
    l->setFixedSize(400,50);
}

void UIEditorWidget::InitListWidget()
{
    //允许拖拽
    ui->kjWidget->setDragEnabled(true);
    ui->windowWidget->setDragEnabled(true);
    connect(ui->kjWidget,&QListWidget::itemDoubleClicked,this,[=](){
        l->setText(ui->kjWidget->currentItem()->text());
        l->show();
    });
    connect(ui->windowWidget,&QListWidget::itemDoubleClicked,this,[=](){
        l->setText(ui->windowWidget->currentItem()->text());
        l->show();
    });
    //点击Item时右边显示Item详情
    connect(ui->kjWidget,&QListWidget::currentRowChanged,this,[=](int row){
        if(row >= ui->kjWidget->count() || row < 0 || ui->kjWidget->count() <= 0)
            return;
        QString name = ui->kjWidget->item(row)->text();
        if(UILib::Instance().labels.contains(name))
        {
            LoadLabel(UILib::Instance().labels[name]);
        }
        else if(UILib::Instance().btns.contains(name))
        {
            LoadButton(UILib::Instance().btns[name]);
        }
    });
    //点击界面时显示界面
    connect(ui->windowWidget,&QListWidget::currentRowChanged,this,[=](int row){
        LoadWidget(row);
    });

    //图鉴
    ui->albumListDockWidget->setFeatures(QDockWidget::AllDockWidgetFeatures);
    ui->albumListDockWidget->setMaximumWidth(500);
    this->addDockWidget(Qt::BottomDockWidgetArea,ui->albumListDockWidget);
    ui->albumListDockWidget->setAllowedAreas(Qt::BottomDockWidgetArea);
    ui->albumListDockWidget->setTitleBarWidget(new QWidget());
    connect(ui->DeleteAlbum,&QPushButton::clicked,this,[=](){
        if(ui->albumList->currentItem())
        {
            QListWidgetItem* item = ui->albumList->currentItem();
            QString path = item->text();
            ui->albumList->takeItem(ui->albumList->currentRow());
            delete item;
            item = nullptr;
            emit EventCenter::Instance().DeleteAlbum(path);
        }
    });
    connect(&EventCenter::Instance(),&EventCenter::RunRecord,this,[=](RecordItem* item){
        if(!item)
        {
            ui->albumList->clear();
            ReadAlbum();
        }
    });
    //文件窗口
    resourceWidget = new ResourcesWidget();
    resourceWidget->setFeatures(QDockWidget::AllDockWidgetFeatures);
    resourceWidget->setMinimumSize(400,400);
    this->addDockWidget(Qt::BottomDockWidgetArea,resourceWidget);
    resourceWidget->setAllowedAreas(Qt::BottomDockWidgetArea);
    resourceWidget->setTitleBarWidget(new QWidget());
}

void UIEditorWidget::LoadLabel(LabelInfo *info)
{
    //恢复默认
    ui->labelImgPath->setText("");
    ui->textEdit->setText("");
    //读取信息并显示
    ui->detailTabWidget->setCurrentIndex(1);
    ui->labelImgPath->setText(info->img);
    ui->textEdit->setText(info->text);
    //显示外观
    QList<MyLabel*>labels = ui->labelLabel->findChildren<MyLabel*>("myLabel");
    if(labels.count() <= 0)
    {
        MyLabel* label = new MyLabel(ui->labelLabel);
        label->setObjectName("myLabel");
        label->Refresh(info);
        label->SetSelectedDisabled(true);
        label->show();
    }
    else
    {
        labels.at(0)->Refresh(info);
    }
    //颜色
    int r = info->color.red();
    int g = info->color.green();
    int b = info->color.blue();
    QString qss = "background-color:rgb(" +
            QString::number(r) + "," +
            QString::number(g) + "," +
            QString::number(b) + ");border:none;";
    colorDialog.setCurrentColor(info->color);
    ui->LabelColor->setStyleSheet(qss);

    ui->detailTabWidget->setTabEnabled(1,true);
    ui->detailTabWidget->setTabEnabled(0,false);
    ui->detailTabWidget->setTabEnabled(2,false);
}

void UIEditorWidget::LoadButton(ButtonInfo *info)
{
    ui->detailTabWidget->setTabEnabled(1,false);
    ui->detailTabWidget->setTabEnabled(0,true);
    ui->detailTabWidget->setTabEnabled(2,false);
    //恢复默认：
    ui->radioButton->setChecked(true);
    QString de = "";
    ui->btnSoundPath->setText(de);
    ui->btnImgPath->setText(de);
    ui->btnInPath->setText(de);
    ui->btnPressPath->setText(de);
    ui->btnText->setText(de);
    ui->openLineEdit->setText(de);
    ui->ButtonColor->setStyleSheet("background-color:black;");

    //读取信息并显示
    ui->detailTabWidget->setCurrentIndex(0);
    ui->radioButton->setChecked(info->interactive);
    ui->btnSoundPath->setText(info->soundPath);
    ui->btnImgPath->setText(info->img);
    ui->btnInPath->setText(info->inImg);
    ui->btnPressPath->setText(info->pressImg);
    ui->btnText->setText(info->text);
    //事件、背景图
    switch(info->event)
    {
    case OPEN:
        ui->openWidgetRadioBtn->setChecked(true);
        ui->openLineEdit->setText(info->eventWidgetName);
        break;
    default:
        ui->normalEventBtn->setChecked(true);
        break;
    }
    //显示外观
    QList<MyButton*>btns = ui->buttonLabel->findChildren<MyButton*>("myButton");
    if(btns.count() <= 0)
    {
        MyButton* b = new MyButton(ui->buttonLabel);
        b->Refresh(info);
        b->setObjectName("myButton");
        b->SetSelectedDisabled(true);
        b->show();
    }
    else
    {
        btns.at(0)->Refresh(info);
    }
    //颜色
    int r = info->color.red();
    int g = info->color.green();
    int b = info->color.blue();
    QString qss = "background-color:rgb(" +
            QString::number(r) + "," +
            QString::number(g) + "," +
            QString::number(b) + ");border:none;";
    colorDialog.setCurrentColor(info->color);
    ui->ButtonColor->setStyleSheet(qss);
}

void UIEditorWidget::LoadWidget(int row)
{
    ui->detailTabWidget->setTabEnabled(0,false);
    ui->detailTabWidget->setTabEnabled(1,false);
    ui->detailTabWidget->setTabEnabled(2,true);
    if(row >= ui->windowWidget->count() || row < 0 || ui->windowWidget->count() <= 0)
        return;
    QString name = ui->windowWidget->item(row)->text();
    if(widgets.contains(name))
    {
        if(curWidget)
        {
            ui->widget->layout()->removeWidget(curWidget);
            curWidget->hide();
        }
        curWidget = widgets[name];
        ui->widget->layout()->addWidget(curWidget);
        ui->widget->layout()->setContentsMargins(0,0,0,0);
        curWidget->show();
    }
    ui->widgetImg->setText(curWidget->bgPath);
    for(auto it = UILib::Instance().layoutMap.begin();it != UILib::Instance().layoutMap.end();it++)
    {
        if(it.value() == widgets[name]->myLayout)
        {
            ui->layout->setCurrentText(it.key());
            break;
        }
    }
}

void UIEditorWidget::InitEditUI()
{
    connect(ui->labelImgPath,&QLineEdit::editingFinished,this,[=](){
        QString lName = ui->kjWidget->currentItem()->text();
        if(UILib::Instance().labels.contains(lName))
        {
            UILib::Instance().labels[lName]->img = ui->labelImgPath->text();
        }
    });
    connect(ui->saveBtnBtn,&QPushButton::clicked,this,[=](){
        SaveBtn();
    });
    connect(ui->saveLabelBtn,&QPushButton::clicked,this,[=](){
        SaveLabel();
    });
    connect(ui->saveWidgetBtn,&QPushButton::clicked,this,[=](){
        SaveWidget();
    });
}

void UIEditorWidget::SaveBtn()
{
    //检查路径是否合法
    bool legal = (ui->btnSoundPath->text().isEmpty() || FileManager::GetFileType(ui->btnSoundPath->text()) == FileManager::SOUND) &&
            (ui->btnImgPath->text().isEmpty() || FileManager::GetFileType(ui->btnImgPath->text()) == FileManager::IMAGE) &&
            (ui->btnInPath->text().isEmpty() || FileManager::GetFileType(ui->btnInPath->text()) == FileManager::IMAGE) &&
            (ui->btnPressPath->text().isEmpty() || FileManager::GetFileType(ui->btnPressPath->text()) == FileManager::IMAGE);

    if(!legal)
    {
        emit EventCenter::Instance().Warning("保存失败，填入的路径不合法！");
        return;
    }
    QString bName = ui->kjWidget->currentItem()->text();
    UILib::Instance().btns[bName]->interactive = ui->radioButton->isChecked();
    UILib::Instance().btns[bName]->soundPath = ui->btnSoundPath->text();
    UILib::Instance().btns[bName]->img = ui->btnImgPath->text();
    UILib::Instance().btns[bName]->inImg = ui->btnInPath->text();
    UILib::Instance().btns[bName]->pressImg = ui->btnPressPath->text();
    UILib::Instance().btns[bName]->text = ui->btnText->text();
    //字体
    UILib::Instance().btns[bName]->font = QFont(ui->ButtonFontBox->currentFont().family(),ui->ButtonFontSize->value());
    UILib::Instance().btns[bName]->color = colorDialog.currentColor();
    if(ui->openWidgetRadioBtn->isChecked())
    {
        UILib::Instance().btns[bName]->event = OPEN;
        UILib::Instance().btns[bName]->eventWidgetName = ui->openLineEdit->text();
    }
    else if(ui->normalEventBtn->isChecked())
    {
        if(ui->eventComboBox->currentText() == "无")
        {
            UILib::Instance().btns[bName]->event = NONE;
        }else if(ui->eventComboBox->currentText() == "退出游戏")
        {
            UILib::Instance().btns[bName]->event = QUIT;
        }
    }
    LoadButton(UILib::Instance().btns[bName]);
    emit EventCenter::Instance().UIChange(bName);
}

void UIEditorWidget::SaveLabel()
{
    if(!ui->labelImgPath->text().isEmpty() &&
        FileManager::GetFileType(ui->labelImgPath->text()) != FileManager::IMAGE)
    {
        emit EventCenter::Instance().Warning("保存失败，填入的路径不合法！");
        return;
    }

    QString lName = ui->kjWidget->currentItem()->text();
    if(!UILib::Instance().labels.contains(lName))
    {
        qDebug()<<"名字不存在，保存失败";
        return;
    }
    UILib::Instance().labels[lName]->color = colorDialog.currentColor();
    UILib::Instance().labels[lName]->img = ui->labelImgPath->text();
    UILib::Instance().labels[lName]->text = ui->textEdit->toHtml();
    LoadLabel(UILib::Instance().labels[lName]);
    emit EventCenter::Instance().UIChange(lName);
}

void UIEditorWidget::SaveWidget()
{
    if(!ui->widgetImg->text().isEmpty() &&
        FileManager::GetFileType(ui->widgetImg->text()) != FileManager::IMAGE)
    {
        emit EventCenter::Instance().Warning("保存失败，填入的路径不合法！");
        return;
    }
    QString name = ui->windowWidget->currentItem()->text();
    if(ui->windowWidget->count() > 0)
    {
        widgets[name]->RefreshBg(ui->widgetImg->text());
    }
    if(UILib::Instance().layoutMap.contains(ui->layout->currentText()))
    {
        widgets[name]->SetLayout(UILib::Instance().layoutMap[ui->layout->currentText()]);
    }
}

void UIEditorWidget::DeleteItem()
{
    //前端
    if(ui->kjWidget->count() <= 0)
        return;
    QString name = ui->kjWidget->currentItem()->text();
    if(UILib::Instance().btnWhiteList.contains(name) || UILib::Instance().labelWhiteList.contains(name))
    {
        return;
    }
    int row = ui->kjWidget->currentRow();
    if(row >= 0 && ui->kjWidget->count() > row + 1)
    {
        ui->kjWidget->setCurrentRow(row+1);
    }
    else if(ui->kjWidget->count() > 1 && row > 0)
    {
        ui->kjWidget->setCurrentRow(row - 1);
    }
    else if(ui->kjWidget->count() == 1)
    {
        ui->kjWidget->clear();
    }

    if(ui->kjWidget->count() > 0)
        ui->kjWidget->takeItem(row);
    //后端
    //界面
    emit EventCenter::Instance().UIDelete(name);
    //UILib
    if(UILib::Instance().labels.contains(name))
    {
        LabelInfo* info = UILib::Instance().labels[name];
        UILib::Instance().labels.remove(name);
        delete info;
    }
    else if(UILib::Instance().btns.contains(name))
    {
        ButtonInfo* info = UILib::Instance().btns[name];
        UILib::Instance().btns.remove(name);
        delete info;
    }
}

void UIEditorWidget::DeleteWidget()
{
    if(ui->windowWidget->count() <= 0)
        return;
    QString name = ui->windowWidget->currentItem()->text();
    if(UILib::Instance().widgetWhiteList.contains(name))
        return;
    int row = ui->windowWidget->currentRow();
    if(row >= 0 && ui->windowWidget->count() > row + 1)
    {
        ui->windowWidget->setCurrentRow(row+1);
    }
    else if(ui->windowWidget->count() > 1 && row > 0)
    {
        ui->windowWidget->setCurrentRow(row - 1);
    }
    else if(ui->windowWidget->count() == 1)
    {
        ui->windowWidget->clear();
    }
    if(ui->windowWidget->count() > 0)
        ui->windowWidget->takeItem(row);
    if(widgets.contains(name))
    {
        MyWidget* w = widgets[name];
        widgets.remove(name);
        delete w;
    }
}

void UIEditorWidget::InformInfo()
{
    if(ui->windowWidget->count() <= 0 || ui->kjWidget->count() <= 0)
        return;
    QString wName = ui->windowWidget->currentItem()->text();
    QString kName = ui->kjWidget->currentItem()->text();
    if(widgets.contains(wName))
    {
        if(UILib::Instance().btns.contains(kName))
        {
           widgets[wName]->SetButton(UILib::Instance().btns[kName]);
        }else if(UILib::Instance().labels.contains(kName))
        {
            widgets[wName]->SetLabel(UILib::Instance().labels[kName]);
        }
    }
}

void UIEditorWidget::Save()
{
    QString btnPath = FileManager::Instance().uiEditorBtnsPath;
    QString labelPath = FileManager::Instance().uiEditorLabelsPath;
    QString interfacePath = FileManager::Instance().uiEditorInterfacesPath;
    JsonTranslator jt;
    //存控件
    QJsonArray jsonlabels;
    QJsonArray jsonbtns;
    for(int i = 0;i < ui->kjWidget->count();i++)
    {
        QString name = ui->kjWidget->item(i)->text();
        if(UILib::Instance().labels.contains(name))
        {
            LabelInfo* info = UILib::Instance().labels[name];
            QJsonObject *ob = jt.ToJson(info);
            jsonlabels.append(*ob);
        }
        else if(UILib::Instance().btns.contains(name))
        {
            ButtonInfo* info = UILib::Instance().btns[name];
            QJsonObject *ob = jt.ToJson(info);
            jsonbtns.append(*ob);
        }
    }
    QJsonObject* labelob = new QJsonObject();
    labelob->insert("labels",jsonlabels);
    FileManager::Instance().Write(labelPath,jt.Json2Byte(labelob));
    QJsonObject* btnob = new QJsonObject();
    btnob->insert("btns",jsonbtns);
    FileManager::Instance().Write(btnPath,jt.Json2Byte(btnob));
    //存widget
    QJsonArray jsonwidgets;
    for(int i = 0;i < ui->windowWidget->count();i++)
    {
        QString name = ui->windowWidget->item(i)->text();
        if(widgets.contains(name))
        {
            QJsonObject* ob = jt.ToJson(widgets[name]);
            if(!ob)
            {
                qDebug()<<ui->windowWidget->item(i)->text()<<"转Json失败";
            }
            jsonwidgets.append(*ob);
        }
    }
    QJsonObject* widgetOb = new QJsonObject();
    widgetOb->insert("widgets",jsonwidgets);
    //当前编号
    widgetOb->insert("id",id);
    FileManager::Instance().Write(interfacePath,jt.Json2Byte(widgetOb));
    //存图鉴
    UIManager::Instance().album->Save();
}

void UIEditorWidget::Load()
{
    //读取所有控件
    QString labelPath = FileManager::Instance().uiEditorLabelsPath;
    QString btnPath = FileManager::Instance().uiEditorBtnsPath;
    QString interfacePath = FileManager::Instance().uiEditorInterfacesPath;

    JsonTranslator jt;

    //labels
    QJsonObject* labelob = FileManager::Instance().ReadJsonFile(labelPath);
    if(labelob)
    {
        QJsonArray labelArray = (*labelob)["labels"].toArray();
        for (int i = 0;i < labelArray.count();i++)
        {
            QJsonObject* ob = new QJsonObject(labelArray[i].toObject());
            LabelInfo* info = jt.LabelInfoFromJson(ob);
            UILib::Instance().labels.insert(info->name,info);
            ui->kjWidget->addItem(info->name);
            if(UILib::Instance().labelWhiteList.contains(info->name))
            {
                ui->kjWidget->item(ui->kjWidget->count() - 1)->setForeground(QBrush(Qt::red));
            }
        }
    }
    //btns
    QJsonObject* btnob = FileManager::Instance().ReadJsonFile(btnPath);
    if(btnob)
    {
        QJsonArray btnArray = (*btnob)["btns"].toArray();
        for (int i = 0;i < btnArray.count();i++)
        {
            QJsonObject* ob = new QJsonObject(btnArray[i].toObject());
            ButtonInfo* info = jt.BtnInfoFromJson(ob);
            UILib::Instance().btns.insert(info->name,info);
            ui->kjWidget->addItem(info->name);
            if(UILib::Instance().btnWhiteList.contains(info->name))
            {
                ui->kjWidget->item(ui->kjWidget->count() - 1)->setForeground(QBrush(Qt::red));
            }
        }
    }

    if(ui->kjWidget->count() > 0)
    {
        ui->kjWidget->setCurrentRow(0);
    }

    //widgets
    QJsonObject* widgetob = FileManager::Instance().ReadJsonFile(interfacePath);
    if(widgetob)
    {
        QJsonArray widgetArray = (*widgetob)["widgets"].toArray();
        for (int i = 0;i < widgetArray.count();i++)
        {
            QJsonObject* ob = new QJsonObject(widgetArray[i].toObject());
            MyWidget* w = jt.WidgetFromJson(ob);
            if(!w)
                continue;
            widgets.insert(w->name,w);
            ui->windowWidget->addItem(w->name);
            if(UILib::Instance().widgetWhiteList.contains(w->name))
                ui->windowWidget->item(ui->windowWidget->count() - 1)->setForeground(QBrush(Qt::red));
        }
        id = (*widgetob)["id"].toInt();
    }

    if(ui->windowWidget->count() > 0)
    {
        ui->windowWidget->setCurrentRow(0);
    }
    InitWhiteList();
}

void UIEditorWidget::InitWhiteList()
{
    QString album = "图鉴",cover = "封面",game = "游戏",record = "存档",data = "数值",menu = "菜单";
    if(!widgets.contains(album) || !widgets[album])
    {
        ui->windowWidget->addItem(album);
        ui->windowWidget->item(ui->windowWidget->count() - 1)->setForeground(QBrush(Qt::red));
    }
    if(!widgets.contains(cover) || !widgets[cover])
    {
        ui->windowWidget->addItem(cover);
        ui->windowWidget->item(ui->windowWidget->count() - 1)->setForeground(QBrush(Qt::red));
    }
    if(!widgets.contains(game) || !widgets[game])
    {
        ui->windowWidget->addItem(game);
        ui->windowWidget->item(ui->windowWidget->count() - 1)->setForeground(QBrush(Qt::red));
    }
    if(!widgets.contains(record) || !widgets[record])
    {
        ui->windowWidget->addItem(record);
        ui->windowWidget->item(ui->windowWidget->count() - 1)->setForeground(QBrush(Qt::red));
    }
    if(!widgets.contains(data) || !widgets[data])
    {
        ui->windowWidget->addItem(data);
        ui->windowWidget->item(ui->windowWidget->count() - 1)->setForeground(QBrush(Qt::red));
    }
    if(!widgets.contains(menu) || !widgets[menu])
    {
        ui->windowWidget->addItem(menu);
        ui->windowWidget->item(ui->windowWidget->count() - 1)->setForeground(QBrush(Qt::red));
    }

    MyWidget* myAlbum = widgets.contains(album)? widgets[album]:new MyWidget();
    DealDefautWidgets(myAlbum,UIManager::Instance().album);
    myAlbum->name = album;
    widgets[album] = myAlbum;

    MyWidget* myCover = widgets.contains(cover)? widgets[cover]:new MyWidget();
    DealDefautWidgets(myCover,UIManager::Instance().coverPage);
    myCover->name = cover;
    widgets[cover] = myCover;

    MyWidget* myGameMainWindow = widgets.contains(game)?widgets[game]:new MyWidget();
    DealDefautWidgets(myGameMainWindow,UIManager::Instance().gameMainWindow);
    myGameMainWindow->name = game;
    widgets[game] = myGameMainWindow;

    MyWidget* myRecord= widgets.contains(record)?widgets[record]:new MyWidget();
    DealDefautWidgets(myRecord,UIManager::Instance().record);
    myRecord->name = record;
    widgets[record] = myRecord;

    MyWidget* myDataview= widgets.contains(data)?widgets[data]:new MyWidget();
    DealDefautWidgets(myDataview,UIManager::Instance().dataView);
    myDataview->name = data;
    widgets[data] = myDataview;

    MyWidget* myMenu= widgets.contains(menu)?widgets[menu]:new MyWidget();
    DealDefautWidgets(myMenu,UIManager::Instance().menu);
    myMenu->name = menu;
    widgets[menu] = myMenu;

    //按钮
    QString menuBtn = "菜单按钮",option = "选项",backHome = "返回主页",backGame = "返回游戏",
            quit = "退出游戏",last = "图鉴-上一张",next = "图鉴-下一张",deleteRecord = "存档-删除存档",
            menu_album = "菜单-查看图鉴",menu_data = "菜单-查看数值",menu_sound = "菜单-语音",
            menu_bgm = "菜单-音乐",menu_bgse = "菜单-音效",cover_game = "封面-开始游戏";
    if(!UILib::Instance().btns.contains(menuBtn) || !UILib::Instance().btns[menuBtn])
    {
        QString img = ":/res/icon/setting.png";
        ButtonInfo* info = new ButtonInfo("",img,img,img);
        info->name = menuBtn;
        info->event = OPEN;
        info->eventWidgetName = menu;
        UILib::Instance().btns[menuBtn] = info;
        ui->kjWidget->addItem(menuBtn);
        ui->kjWidget->item(ui->kjWidget->count() - 1)->setForeground(QBrush(Qt::red));
    }
    if(!UILib::Instance().btns.contains(option) || !UILib::Instance().btns[option])
    {
        ButtonInfo* info = new ButtonInfo();
        info->name = option;
        UILib::Instance().btns[option] = info;
        ui->kjWidget->addItem(option);
        ui->kjWidget->item(ui->kjWidget->count() - 1)->setForeground(QBrush(Qt::red));
    }
    if(!UILib::Instance().btns.contains(backHome) || !UILib::Instance().btns[backHome])
    {
        QString img = ":/res/icon/backHome.png";
        ButtonInfo* info = new ButtonInfo("",img,img,img);
        info->name = backHome;
        info->event = OPEN;
        info->eventWidgetName = cover;
        UILib::Instance().btns[backHome] = info;
        ui->kjWidget->addItem(backHome);
        ui->kjWidget->item(ui->kjWidget->count() - 1)->setForeground(QBrush(Qt::red));
    }
    if(!UILib::Instance().btns.contains(backGame) || !UILib::Instance().btns[backHome])
    {
        QString img = ":/res/icon/back.png";
        ButtonInfo* info = new ButtonInfo("",img,img,img);
        info->name = backGame;
        info->event = OPEN;
        info->eventWidgetName = game;
        UILib::Instance().btns[backGame] = info;
        ui->kjWidget->addItem(backGame);
        ui->kjWidget->item(ui->kjWidget->count() - 1)->setForeground(QBrush(Qt::red));
    }
    if(!UILib::Instance().btns.contains(quit) || !UILib::Instance().btns[quit])
    {
        QString img = ":/res/icon/quit.png";
        ButtonInfo* info = new ButtonInfo("",img,img,img);
        info->name = quit;
        info->event = QUIT;
        UILib::Instance().btns[quit] = info;
        ui->kjWidget->addItem(quit);
        ui->kjWidget->item(ui->kjWidget->count() - 1)->setForeground(QBrush(Qt::red));
    }
    if(!UILib::Instance().btns.contains(last) || !UILib::Instance().btns[last])
    {
        QString img = ":/res/icon/left.png";
        ButtonInfo* info = new ButtonInfo("",img,img,img);
        info->name = last;
        UILib::Instance().btns[last] = info;
        ui->kjWidget->addItem(last);
        ui->kjWidget->item(ui->kjWidget->count() - 1)->setForeground(QBrush(Qt::red));
    }
    if(!UILib::Instance().btns.contains(next) || !UILib::Instance().btns[next])
    {
        QString img = ":/res/icon/right.png";
        ButtonInfo* info = new ButtonInfo("",img,img,img);
        info->name = next;
        UILib::Instance().btns[next] = info;
        ui->kjWidget->addItem(next);
        ui->kjWidget->item(ui->kjWidget->count() - 1)->setForeground(QBrush(Qt::red));
    }
    if(!UILib::Instance().btns.contains(deleteRecord) || !UILib::Instance().btns[deleteRecord])
    {
        QString img = ":/res/icon/close.png";
        ButtonInfo* info = new ButtonInfo("",img,img,img);
        info->name = deleteRecord;
        UILib::Instance().btns[deleteRecord] = info;
        ui->kjWidget->addItem(deleteRecord);
        ui->kjWidget->item(ui->kjWidget->count() - 1)->setForeground(QBrush(Qt::red));
    }
    if(!UILib::Instance().btns.contains(menu_album) || !UILib::Instance().btns[menu_album])
    {
        QString img = ":/res/UI/button2.png";
        ButtonInfo* info = new ButtonInfo("",img,img,img);
        info->text = "CG鉴赏";
        info->name = menu_album;
        info->event = OPEN;
        info->eventWidgetName = album;
        info->color = QColor("white");
        UILib::Instance().btns[menu_album] = info;
        ui->kjWidget->addItem(menu_album);
        ui->kjWidget->item(ui->kjWidget->count() - 1)->setForeground(QBrush(Qt::red));
    }
    if(!UILib::Instance().btns.contains(menu_data) || !UILib::Instance().btns[menu_data])
    {
        QString img = ":/res/UI/button2.png";
        ButtonInfo* info = new ButtonInfo("",img,img,img);
        info->text = "属性数值";
        info->name = menu_data;
        info->event = OPEN;
        info->eventWidgetName = data;
        info->color = QColor("white");
        UILib::Instance().btns[menu_data] = info;
        ui->kjWidget->addItem(menu_data);
        ui->kjWidget->item(ui->kjWidget->count() - 1)->setForeground(QBrush(Qt::red));
    }
    if(!UILib::Instance().btns.contains(menu_sound) || !UILib::Instance().btns[menu_sound])
    {
        ButtonInfo* info = new ButtonInfo("","","","");
        info->text = "语音";
        info->name = menu_sound;
        info->interactive = false;
        info->color = QColor("white");
        UILib::Instance().btns[menu_sound] = info;
        ui->kjWidget->addItem(menu_sound);
        ui->kjWidget->item(ui->kjWidget->count() - 1)->setForeground(QBrush(Qt::red));
    }
    if(!UILib::Instance().btns.contains(menu_bgm) || !UILib::Instance().btns[menu_bgm])
    {
        ButtonInfo* info = new ButtonInfo("","","","");
        info->text = "音乐";
        info->name = menu_bgm;
        info->interactive = false;
        info->color = QColor("white");
        UILib::Instance().btns[menu_bgm] = info;
        ui->kjWidget->addItem(menu_bgm);
        ui->kjWidget->item(ui->kjWidget->count() - 1)->setForeground(QBrush(Qt::red));
    }
    if(!UILib::Instance().btns.contains(menu_bgse) || !UILib::Instance().btns[menu_bgse])
    {
        ButtonInfo* info = new ButtonInfo("","","","");
        info->text = "音效";
        info->name = menu_bgse;
        info->interactive = false;
        info->color = QColor("white");
        UILib::Instance().btns[menu_bgse] = info;
        ui->kjWidget->addItem(menu_bgse);
        ui->kjWidget->item(ui->kjWidget->count() - 1)->setForeground(QBrush(Qt::red));
    }
    if(!UILib::Instance().btns.contains(cover_game) || !UILib::Instance().btns[cover_game])
    {
        QString img = ":/res/UI/button2.png";
        ButtonInfo* info = new ButtonInfo("",img,img,img);
        info->text = "开始游戏";
        info->name = cover_game;
        info->event = OPEN;
        info->eventWidgetName = record;
        info->color = QColor("white");
        UILib::Instance().btns[cover_game] = info;
        ui->kjWidget->addItem(cover_game);
        ui->kjWidget->item(ui->kjWidget->count() - 1)->setForeground(QBrush(Qt::red));
    }

    //容器
    QString gameCharacter = "游戏-角色名",gameDialog = "游戏-对话框",
            recordImg = "存档-存档框",albumContainer = "图鉴-容器",recordContainer = "存档-容器",
            dataImg = "数值-容器",dataContainer = "数值-数值框",addRecord = "存档-添加存档";
    if(!UILib::Instance().labels.contains(gameCharacter) || !UILib::Instance().labels[gameCharacter])
    {
        QString img = ":/res/UI/button.png";
        LabelInfo* info = new LabelInfo(gameCharacter,img,"角色");
        UILib::Instance().labels[gameCharacter] = info;
        ui->kjWidget->addItem(gameCharacter);
        ui->kjWidget->item(ui->kjWidget->count() - 1)->setForeground(QBrush(Qt::red));
    }
    if(!UILib::Instance().labels.contains(gameDialog) || !UILib::Instance().labels[gameDialog])
    {
        QString img = ":/res/UI/dialog.png";
        LabelInfo* info = new LabelInfo(gameDialog,img,"对话");
        UILib::Instance().labels[gameDialog] = info;
        ui->kjWidget->addItem(gameDialog);
        ui->kjWidget->item(ui->kjWidget->count() - 1)->setForeground(QBrush(Qt::red));
    }
    if(!UILib::Instance().labels.contains(recordImg) || !UILib::Instance().labels[recordImg])
    {
        QString img = ":/res/UI/dialog.png";
        LabelInfo* info = new LabelInfo(recordImg,img,"");
        UILib::Instance().labels[recordImg] = info;
        ui->kjWidget->addItem(recordImg);
        ui->kjWidget->item(ui->kjWidget->count() - 1)->setForeground(QBrush(Qt::red));
    }
    if(!UILib::Instance().labels.contains(dataImg) || !UILib::Instance().labels[dataImg])
    {
        QString img = ":/res/UI/dialog.png";
        LabelInfo* info = new LabelInfo(dataImg,img,"");
        UILib::Instance().labels[dataImg] = info;
        ui->kjWidget->addItem(dataImg);
        ui->kjWidget->item(ui->kjWidget->count() - 1)->setForeground(QBrush(Qt::red));
    }
    if(!UILib::Instance().labels.contains(albumContainer) || !UILib::Instance().labels[albumContainer])
    {
        QString img = ":/res/UI/dialog.png";
        LabelInfo* info = new LabelInfo(albumContainer,img,"");
        UILib::Instance().labels[albumContainer] = info;
        ui->kjWidget->addItem(albumContainer);
        ui->kjWidget->item(ui->kjWidget->count() - 1)->setForeground(QBrush(Qt::red));
    }
    if(!UILib::Instance().labels.contains(recordContainer) || !UILib::Instance().labels[recordContainer])
    {
        QString img = ":/res/UI/dialog.png";
        LabelInfo* info = new LabelInfo(recordContainer,img,"");
        UILib::Instance().labels[recordContainer] = info;
        ui->kjWidget->addItem(recordContainer);
        ui->kjWidget->item(ui->kjWidget->count() - 1)->setForeground(QBrush(Qt::red));
    }
    if(!UILib::Instance().labels.contains(dataContainer) || !UILib::Instance().labels[dataContainer])
    {
        QString img = ":/res/UI/dialog.png";
        LabelInfo* info = new LabelInfo(dataContainer,img,"");
        UILib::Instance().labels[dataContainer] = info;
        ui->kjWidget->addItem(dataContainer);
        ui->kjWidget->item(ui->kjWidget->count() - 1)->setForeground(QBrush(Qt::red));
    }
    if(!UILib::Instance().labels.contains(addRecord) || !UILib::Instance().labels[addRecord])
    {
        QString img = ":/res/UI/addRecord.png";
        LabelInfo* info = new LabelInfo(addRecord,img,"");
        UILib::Instance().labels[addRecord] = info;
        ui->kjWidget->addItem(addRecord);
        ui->kjWidget->item(ui->kjWidget->count() - 1)->setForeground(QBrush(Qt::red));
    }
    InitWhiteListWidgetBackGround();
    ReadAlbum();
}

void UIEditorWidget::ReadAlbum()
{
    QJsonObject* ob = FileManager::Instance().ReadJsonFile(FileManager::Instance().albumPath);
    if(!ob)
    {
        return;
    }
    JsonTranslator jt;
    QVector<QString> v = jt.StringVectorFromJson(ob);
    for(int i = 0;i < v.count();i++)
    {
        QString path = v[i];
        ui->albumList->addItem(path);
        ui->albumList->item(ui->albumList->count() - 1)->setToolTip(path);
        emit EventCenter::Instance().AddAlbum(path);
    }
}

void UIEditorWidget::InitWhiteListWidgetBackGround()
{
    for(int i = 0;i < UILib::Instance().widgetWhiteList.count();i++)
    {
        QString name = UILib::Instance().widgetWhiteList[i];
    }
}

void UIEditorWidget::DealDefautWidgets(MyWidget *m, QWidget *w)
{
    if(!w)
        return;
    if(!m)
        m = new MyWidget();
    m->setLayout(new QHBoxLayout());
    m->layout()->setContentsMargins(0,0,0,0);
    m->layout()->addWidget(w);
    w->setParent(m);
    w->lower();
}

void UIEditorWidget::EditFinished()
{
    if(UILib::Instance().labels.contains(l->text()) || UILib::Instance().btns.contains(l->text()) || widgets.contains(l->text()))
    {
        emit EventCenter::Instance().Warning(l->text() + "已存在，请重新命名");
        return;
    }
    if(ui->tabWidget->currentIndex() == 0)
    {
        QString name = ui->kjWidget->currentItem()->text();
        ui->kjWidget->currentItem()->setText(l->text());
        if(UILib::Instance().labels.contains(name))
        {
            UILib::Instance().labels.insert(l->text(),UILib::Instance().labels[name]);
            UILib::Instance().labels[name]->name = l->text();
            UILib::Instance().labels.remove(name);
        }
        else if(UILib::Instance().btns.contains(name))
        {
            UILib::Instance().btns.insert(l->text(),UILib::Instance().btns[name]);
            UILib::Instance().btns[name]->name = l->text();
            UILib::Instance().btns.remove(name);
        }
    }
    else
    {
        ui->windowWidget->currentItem()->setText(l->text());
        QString name = ui->windowWidget->currentItem()->text();
    }
}
